﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Castle.Core.Interceptor;

namespace WcfPOXCommunication
{
    public class ResponseProcessor : IResponseProcessor
    {
        //TODO: Finish Implementation
        //TODO: code unit tests
        public ServiceResponse Encode(ServiceRequest request, object data)
        {
            if (data != null)
            {
                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    var serializer = new XmlSerializer(data.GetType(), data.GetType().Name);
                    serializer.Serialize(sw, data);
                }
                return new ServiceResponse
                {
                    Success = true,
                    Result = sb.ToString(),
                    ErrorMessage = "",
                    FaultType = ""
                };
            }
            return new ServiceResponse
            {
                Success = true,
                Result = null,
                ErrorMessage = "",
                FaultType = ""
            };
        }

        //TODO: Finish Implementation
        //TODO: code unit tests
        public ServiceResponseSpecification Decode(IInvocation invocation, ServiceResponse response)
        {
            var serializer = new XmlSerializer(invocation.Method.ReturnType,
                invocation.Method.ReturnType.Name);
            object result = null;
            if (response.Success)
            {
                using (var sr = new StringReader(response.Result))
                {
                    result = serializer.Deserialize(sr);
                }
            }

            return new ServiceResponseSpecification
            {
                Success = response.Success,
                ErrorMessage = response.ErrorMessage,
                FaultType = Type.GetType(response.FaultType),
                Result = result
            };
        }
    }
}